# coding = utf-8
import socket
import time

class ServerSocket:
    def __init__(self):
        self.Server = socket.socket()
        self.total_data = bytes()
    def waitconnect(self):
        self.Server.bind(("0.0.0.0",5000))
        self.Server.listen(1)
        print("waiting connect...")
        Client,Address = self.Server.accept()
        print("client address:{}".format(Address))
        return Client

    def receive(self,Client):
        total_len=0
        # Client.setblocking(False)
        while True:
            try:
                message_len_byte = Client.recv(2)
                message_len = message_len_byte[0]<<8 | message_len_byte[1]
                if message_len == 0xFFFF:
                    print("Recved end flag")
                    Client.send(bytes([0xEE,0xEE]))
                    time.sleep(1)
                    # Client.close()
                    return 0
                if not message_len_byte:
                    total_len=0
                    message_len=0
                    self.total_data = b''
                    self.Client.close()
                    self.Server.close()
                    return 0
                print("message_len:{}".format(message_len))
                while True:
                    data = Client.recv(1024)
                    if not data:
                        self.Client.close()
                        self.Server.close()
                        break
                    print("rece data len : {}".format(len(data)))
                    self.total_data += data
                    total_len += len(data)
                    if total_len == message_len:
                        total_len=0
                        message_len=0
                        break
                break
            except Exception as e:
                print(f"error: {e}")
                self.Client.close()
                self.Server.close()
                self.total_data = b''
                total_len=0
                message_len=0
                break
        return self.total_data

    def unpack(self):
        # print(self.total_data[0],self.total_data[-1])
        global name_list
        global name_id
        name = None
        Id = None
        frame = None
        if self.total_data[0] == ord(b'\xaa') and self.total_data[-1] == ord(b'\xbb'):
            NameLenIndex = 1
            NameLen = self.total_data[NameLenIndex]
            IdLenIndex = 3 + NameLen -1
            IdLen = self.total_data[IdLenIndex]
            FrameLenIndex = 5 + NameLen -1
            FrameLenHigh = self.total_data[FrameLenIndex]
            FrameLenLow = self.total_data[FrameLenIndex+1]
            FrameLen = FrameLenHigh<<8 | FrameLenLow
            print("NameLen:{},IdLen:{},FrameLen:{}".format(NameLen,IdLen,FrameLen))
            name = self.total_data[NameLenIndex+1:NameLenIndex+NameLen+1]
            name = name.decode('utf-8')
            Id = self.total_data[IdLenIndex+1:IdLenIndex+IdLen+1]
            Id = int.from_bytes(Id, byteorder='big')
            frame = self.total_data[FrameLenIndex+2:-1]
        
            if name not in name_list.keys():
                name_list[name] = name_id
                name_id += 1

            self.total_data = b''
        return name,Id,frame

if __name__ == "__main__":
    name_list = {}
    name_id = 0
    Server = ServerSocket()
    Client = Server.waitconnect()
    while True:
        data = Server.receive(Client)
        if data:
            name,ID,frame = Server.unpack()
            print(name,ID)
            print(name_list)
            file = open('./FaceData/{}.{}.{}.jpg'.format(name,name_list[name],ID), 'wb') 
            file.write(frame)
        if data == 0:
            Client.close()
            Server.Server.close()
            break
